import React, { useEffect, useState } from "react";
import { Card, Form, Input, Select, Row, Col  } from "antd";
import { isEmptyObj } from "@/utils/util";
import { useComponentDidMount } from "@/hooks";
import { companyTypes } from "@/constants/types";
import { fetchCustomerOptions, fetchCustomerStaffsOptions } from '../../services';

const { Item } = Form;

const rules = [{required: true}];
const labelCol = {span: 6}

const CompanyInfo = ({form, originData, isPreOrderConvertOrder}: any) => {
  const [companyList, setCompanyList] = useState<companyTypes []>([]);
  const [contacts, setContacts] = useState([]);


  const customerCode = Form.useWatch('customerCode', form);


  // 根据客户查询下单手机
  const handleCompanyChange = (company: any) => {
    form.setFieldsValue({
      customerName: companyList?.find((v: any) => v.value === company)?.label,
      userId: undefined
    });
  }

  const handleContactChange= (userId: string) => {
    const curr = contacts.find((v: any) => v.value === userId);
    if (curr) {
      form.setFieldsValue({
        mobile: curr?.mobile,
        contacts: curr?.name
      });
    } else {
      form.setFieldsValue({
        mobile: undefined,
        contacts: undefined,
      });
    }
  }

  useEffect(() => {
    if (customerCode) {
      fetchCustomerStaffsOptions({id: customerCode}).then(
        res => {
          setContacts((res || []).map((v: any) => ({
            ...v,
            value: v?.userId,
            label: `${v.mobile} - ${v.name}`
          })));
        }
      )
    } else {
      setContacts([]);
    }
  }, [customerCode]);

  useComponentDidMount(() => {
    if (isEmptyObj(originData)) {
      fetchCustomerOptions({customerName: ""}).then(
        res => {
          setCompanyList((res || []).map((v: any) => ({
            ...v,
            label: v?.nickName,
            value: v?.code
          })));
        }
      )
    }
  });

  return (
    <Card title="下单账户">
      <Form form={form} labelCol={labelCol}>
        <Row gutter={20}>
          <Col span={12}>
            <Item label="公司名称" name="customerCode" rules={rules}>
              <Select allowClear showSearch optionFilterProp="label" onChange={handleCompanyChange} options={companyList} disabled={isPreOrderConvertOrder} />
            </Item>
            <Item noStyle hidden name="customerName">
              <Input />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="联系人" name="userId" rules={rules}>
              <Select showSearch optionFilterProp="label" onChange={handleContactChange} options={contacts} disabled={isPreOrderConvertOrder} />
            </Item>
            <Item noStyle hidden name="mobile">
              <Input />
            </Item>
            <Item noStyle hidden name="contacts">
              <Input />
            </Item>
          </Col>
        </Row>
      </Form>
    </Card>
  );
}
export default CompanyInfo;